package cn.kduck.assembler.security.authentication.web;

import cn.kduck.assembler.security.authentication.AuthenticationType;
import cn.kduck.assembler.security.authentication.CaptchaSender;
import cn.kduck.assembler.security.authentication.PhoneNumAuthenticationFilter;
import cn.kduck.core.cache.CacheHelper;
import cn.kduck.core.web.json.JsonObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.SecureRandom;

@RestController
public class PhoneNumAuthenticationController {

    private final Log logger = LogFactory.getLog(getClass());

    private final CaptchaSender captchaSender;

    public PhoneNumAuthenticationController(CaptchaSender captchaSender){
        this.captchaSender = captchaSender;
    }

    @GetMapping("/phone/login/captcha")
    public JsonObject getCaptcha(@RequestParam("phoneNum") String phoneNum){

        Object sleep = CacheHelper.getByCacheName(PhoneNumAuthenticationFilter.class.getSimpleName(), phoneNum + "#SLEEP");

        if(!ObjectUtils.isEmpty(sleep)){
            return new JsonObject(null,-1,"获取验证码操作太频繁，请稍后再试");
        }
        String captcha = randomCaptcha(6);

        try{
            captchaSender.sendCaptcha(AuthenticationType.PHONE_NUM,captcha,phoneNum);
        }catch (Exception exception){
            logger.error("发送短信验证码失败：" + phoneNum,exception);
            return new JsonObject(phoneNum,-1,"发送短信验证码失败");
        }

//        System.out.println("手机登录验证码：" + captcha);

        CacheHelper.put(PhoneNumAuthenticationFilter.class.getSimpleName() , phoneNum,captcha,300);
        CacheHelper.put(PhoneNumAuthenticationFilter.class.getSimpleName() , phoneNum+"#SLEEP",captcha,60);
        return JsonObject.SUCCESS;
    }

    private String randomCaptcha(int len){
        StringBuilder captchaBuilder = new StringBuilder();
        SecureRandom secureRandom = new SecureRandom();
        for (int i = 0; i < len; i++) {
            captchaBuilder.append(secureRandom.nextInt(10));
        }
        return captchaBuilder.toString();
    }
}
